<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>图书管理系统</title>
    <!-- Bootstrap CSS -->
    <link href="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/5.1.3/css/bootstrap.min.css" rel="stylesheet">
    <!-- Bootstrap Icons -->
    <link href="https://cdn.bootcdn.net/ajax/libs/bootstrap-icons/1.8.1/font/bootstrap-icons.css" rel="stylesheet">
    <style>
        .table-actions {
            white-space: nowrap;
        }
        .modal-header {
            background-color: #f8f9fa;
        }
    </style>
</head>
<body>
    <nav class="navbar navbar-expand-lg navbar-dark bg-primary mb-4">
        <div class="container">
            <a class="navbar-brand" href="#">图书管理系统</a>
        </div>
    </nav>

    <div class="container">
        <div class="card">
            <div class="card-header d-flex justify-content-between align-items-center">
                <h5 class="mb-0">图书列表</h5>
                <div>
                    <button onclick="showAddModal()" class="btn btn-primary">
                        <i class="bi bi-plus-lg"></i> 添加图书
                    </button>
                    <button onclick="exportToExcel()" class="btn btn-success">
                        <i class="bi bi-file-earmark-excel"></i> 导出Excel
                    </button>
                </div>
            </div>
            <div class="card-body">
                <div class="table-responsive">
                    <table class="table table-striped table-hover">
                        <thead>
                            <tr>
                                <th>ID</th>
                                <th>书名</th>
                                <th>作者</th>
                                <th>出版社</th>
                                <th>价格</th>
                                <th>库存</th>
                                <th>操作</th>
                            </tr>
                        </thead>
                        <tbody id="bookList">
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>

    <!-- 添加/编辑图书的模态框 -->
    <div class="modal fade" id="bookModal" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="modalTitle">添加图书</h5>
                    <button type="button" class="btn-close" onclick="closeModal()"></button>
                </div>
                <div class="modal-body">
                    <form id="bookForm" class="needs-validation" novalidate>
                        <input type="hidden" id="bookId">
                        <div class="mb-3">
                            <label for="name" class="form-label">书名</label>
                            <input type="text" class="form-control" id="name" required>
                            <div class="invalid-feedback">
                                请输入书名
                            </div>
                        </div>
                        <div class="mb-3">
                            <label for="author" class="form-label">作者</label>
                            <input type="text" class="form-control" id="author">
                        </div>
                        <div class="mb-3">
                            <label for="publisher" class="form-label">出版社</label>
                            <input type="text" class="form-control" id="publisher">
                        </div>
                        <div class="mb-3">
                            <label for="price" class="form-label">价格</label>
                            <input type="number" class="form-control" id="price" step="0.01" min="0">
                        </div>
                        <div class="mb-3">
                            <label for="stock" class="form-label">库存</label>
                            <input type="number" class="form-control" id="stock" min="0">
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" onclick="closeModal()">取消</button>
                    <button type="button" class="btn btn-primary" onclick="saveBook()">保存</button>
                </div>
            </div>
        </div>
    </div>

    <!-- Bootstrap JS -->
    <script src="https://cdn.bootcdn.net/ajax/libs/bootstrap/5.1.3/js/bootstrap.bundle.min.js"></script>
    <script>
        let bookModal;
        
        window.onload = function() {
            bookModal = new bootstrap.Modal(document.getElementById('bookModal'));
            loadBooks();
        };

        function loadBooks() {
            fetch('/api/books')
                .then(response => response.json())
                .then(data => {
                    const bookList = document.getElementById('bookList');
                    bookList.innerHTML = '';
                    data.forEach(book => {
                        const bookStr = JSON.stringify(book).replace(/"/g, '&quot;');
                        bookList.innerHTML += `
                            <tr>
                                <td>${book.id}</td>
                                <td>${book.name || ''}</td>
                                <td>${book.author || ''}</td>
                                <td>${book.publisher || ''}</td>
                                <td>￥${book.price?.toFixed(2) || '0.00'}</td>
                                <td>${book.stock || '0'}</td>
                                <td class="table-actions">
                                    <button onclick='editBook(${bookStr})' class="btn btn-sm btn-outline-primary">
                                        <i class="bi bi-pencil"></i> 编辑
                                    </button>
                                    <button onclick='deleteBook(${book.id})' class="btn btn-sm btn-outline-danger">
                                        <i class="bi bi-trash"></i> 删除
                                    </button>
                                </td>
                            </tr>
                        `;
                    });
                })
                .catch(error => showAlert('加载图书列表失败：' + error, 'danger'));
        }

        function showAddModal() {
            document.getElementById('modalTitle').textContent = '添加图书';
            document.getElementById('bookId').value = '';
            document.getElementById('bookForm').reset();
            bookModal.show();
        }

        function editBook(book) {
            document.getElementById('modalTitle').textContent = '编辑图书';
            document.getElementById('bookId').value = book.id;
            document.getElementById('name').value = book.name || '';
            document.getElementById('author').value = book.author || '';
            document.getElementById('publisher').value = book.publisher || '';
            document.getElementById('price').value = book.price || '';
            document.getElementById('stock').value = book.stock || '';
            bookModal.show();
        }

        function closeModal() {
            bookModal.hide();
        }

        function saveBook() {
            const form = document.getElementById('bookForm');
            if (!form.checkValidity()) {
                form.classList.add('was-validated');
                return;
            }

            const bookId = document.getElementById('bookId').value;
            const book = {
                id: bookId || null,
                name: document.getElementById('name').value,
                author: document.getElementById('author').value,
                publisher: document.getElementById('publisher').value,
                price: parseFloat(document.getElementById('price').value) || 0,
                stock: parseInt(document.getElementById('stock').value) || 0
            };

            const url = book.id ? `/api/books/${book.id}` : '/api/books';
            const method = book.id ? 'PUT' : 'POST';

            fetch(url, {
                method: method,
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(book)
            })
            .then(response => {
                if (!response.ok) {
                    throw new Error('保存失败');
                }
                return response.json();
            })
            .then(() => {
                closeModal();
                loadBooks();
                showAlert('保存成功！', 'success');
            })
            .catch(error => showAlert('保存失败：' + error.message, 'danger'));
        }

        function deleteBook(id) {
            if (confirm('确定要删除这本书吗？')) {
                fetch(`/api/books/${id}`, {
                    method: 'DELETE'
                })
                .then(response => {
                    if (!response.ok) {
                        throw new Error('删除失败');
                    }
                    loadBooks();
                    showAlert('删除成功！', 'success');
                })
                .catch(error => showAlert('删除失败：' + error.message, 'danger'));
            }
        }

        function exportToExcel() {
            window.location.href = '/api/books/export';
        }

        function showAlert(message, type) {
            const alertDiv = document.createElement('div');
            alertDiv.className = `alert alert-${type} alert-dismissible fade show position-fixed top-0 end-0 m-3`;
            alertDiv.innerHTML = `
                ${message}
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            `;
            document.body.appendChild(alertDiv);
            setTimeout(() => alertDiv.remove(), 3000);
        }
    </script>
</body>
</html>